﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using PLC.Forms;
using LiveCharts;
using LiveCharts.Configurations;
using LiveCharts.Wpf;
using S7.Net;
using System.Diagnostics;
using 际海环境软件.Forms;
using 际海环境软件.Class;
using System.Drawing;
using System.Windows.Media;
using System.Windows;
using System.Threading.Tasks;

namespace PLC
{
    public partial class Form1 : Form
    {
        Plc S7200SMART = new Plc(CpuType.S71200, ipaddr, 0, 1);
        Plc S7200SMART1 = new Plc(CpuType.S71200, ipaddr1, 0, 1);
        public ChartValues<MeasureModel> ChartValues { get; set; }
        public ChartValues<MeasureModel> ChartValues1 { get; set; }
        public ChartValues<MeasureModel> ChartValues2 { get; set; }
       
        public static string IP { get; private set; } = 际海环境软件.Properties.Settings.Default.PlcIP;
        public static string IP1 { get; private set; } = 际海环境软件.Properties.Settings.Default.PlcIP1;
        public static string MysqlCon { get; private set; } = 际海环境软件.Properties.Settings.Default.MySqlCon;
        public static int Tim { get; private set; } = 际海环境软件.Properties.Settings.Default.time;
        public static string ipaddr = IP;
        public static string ipaddr1 = IP1;
        public static bool isRegist = false;

        public Form1()
        {
            InitializeComponent();
            #region angularGauge1
            angularGauge1.Value = 0;
            angularGauge1.FromValue = -20;
            angularGauge1.ToValue = 60;
            angularGauge1.Wedge = 180;          
            angularGauge1.NeedleFill= System.Windows.Media.Brushes.White;
            angularGauge1.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge1.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge1.Base.FontWeight = FontWeights.Bold;
            angularGauge1.Base.FontSize = 12;
            angularGauge1.SectionsInnerRadius = 0.5;
            angularGauge1.LabelsStep = 10;
            angularGauge1.TickStep = 5;

            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue = -20,
                ToValue = 10,
                Fill =new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue = 10,
                ToValue = 30,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge1.Sections.Add(new AngularSection
            {
                FromValue = 30,
                ToValue = 60,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge2
            angularGauge2.Value = 0;
            angularGauge2.FromValue = 0;
            angularGauge2.ToValue = 100;
            angularGauge2.Wedge = 180;
            angularGauge2.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge2.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge2.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge2.Base.FontWeight = FontWeights.Bold;
            angularGauge2.Base.FontSize = 12;
            angularGauge2.SectionsInnerRadius = 0.5;
            angularGauge2.LabelsStep = 20;
            angularGauge2.TickStep = 10;

            angularGauge2.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue =40,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });
            angularGauge2.Sections.Add(new AngularSection
            {
                FromValue = 40,
                ToValue = 80,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge2.Sections.Add(new AngularSection
            {
                FromValue = 80,
                ToValue = 100,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge3
            angularGauge3.Value = 0;
            angularGauge3.FromValue = 0;
            angularGauge3.ToValue = 3;
            angularGauge3.Wedge = 180;
            angularGauge3.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge3.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge3.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge3.Base.FontWeight = FontWeights.Bold;
            angularGauge3.Base.FontSize = 12;
            angularGauge3.SectionsInnerRadius = 0.5;
            angularGauge3.LabelsStep = 0.5;
            angularGauge3.TickStep = 0.25;
            angularGauge3.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue = 1,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge3.Sections.Add(new AngularSection
            {
                FromValue = 1,
                ToValue = 2,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge3.Sections.Add(new AngularSection
            {
                FromValue = 2,
                ToValue = 3,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge4
            angularGauge4.Value = 0;
            angularGauge4.FromValue = 0;
            angularGauge4.ToValue = 3;
            angularGauge4.Wedge = 180;
            angularGauge4.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge4.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge4.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge4.Base.FontWeight = FontWeights.Bold;
            angularGauge4.Base.FontSize = 12;
            angularGauge4.SectionsInnerRadius = 0.5;
            angularGauge4.LabelsStep = 0.5;
            angularGauge4.TickStep = 0.25;
            angularGauge4.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue = 1,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge4.Sections.Add(new AngularSection
            {
                FromValue = 1,
                ToValue = 2,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge4.Sections.Add(new AngularSection
            {
                FromValue = 2,
                ToValue = 3,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });

            #endregion
            #region angularGauge5
            angularGauge5.Value = 0;
            angularGauge5.FromValue = -20;
            angularGauge5.ToValue = 60;
            angularGauge5.Wedge = 180;
            angularGauge5.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge5.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge5.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge5.Base.FontWeight = FontWeights.Bold;
            angularGauge5.Base.FontSize = 12;
            angularGauge5.SectionsInnerRadius = 0.5;
            angularGauge5.LabelsStep = 10;
            angularGauge5.TickStep = 5;

            angularGauge5.Sections.Add(new AngularSection
            {
                FromValue = -20,
                ToValue = 10,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge5.Sections.Add(new AngularSection
            {
                FromValue = 10,
                ToValue = 30,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge5.Sections.Add(new AngularSection
            {
                FromValue = 30,
                ToValue = 60,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge6
            angularGauge6.Value = 0;
            angularGauge6.FromValue = 0;
            angularGauge6.ToValue = 100;
            angularGauge6.Wedge = 180;
            angularGauge6.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge6.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge6.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge6.Base.FontWeight = FontWeights.Bold;
            angularGauge6.Base.FontSize = 12;
            angularGauge6.SectionsInnerRadius = 0.5;
            angularGauge6.LabelsStep = 20;
            angularGauge6.TickStep = 10;

            angularGauge6.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue = 40,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });
            angularGauge6.Sections.Add(new AngularSection
            {
                FromValue = 40,
                ToValue = 80,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge6.Sections.Add(new AngularSection
            {
                FromValue = 80,
                ToValue = 100,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge7
            angularGauge7.Value = 0;
            angularGauge7.FromValue = 0;
            angularGauge7.ToValue = 3;
            angularGauge7.Wedge = 180;
            angularGauge7.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge7.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge7.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge7.Base.FontWeight = FontWeights.Bold;
            angularGauge7.Base.FontSize = 12;
            angularGauge7.SectionsInnerRadius = 0.5;
            angularGauge7.LabelsStep = 0.5;
            angularGauge7.TickStep = 0.25;
            angularGauge7.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue = 1,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge7.Sections.Add(new AngularSection
            {
                FromValue = 1,
                ToValue = 2,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge7.Sections.Add(new AngularSection
            {
                FromValue = 2,
                ToValue = 3,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });
            #endregion
            #region angularGauge8
            angularGauge8.Value = 0;
            angularGauge8.FromValue = 0;
            angularGauge8.ToValue = 3;
            angularGauge8.Wedge = 180;
            angularGauge8.NeedleFill = System.Windows.Media.Brushes.White;
            angularGauge8.TicksForeground = System.Windows.Media.Brushes.White;
            angularGauge8.Base.Foreground = System.Windows.Media.Brushes.White;
            angularGauge8.Base.FontWeight = FontWeights.Bold;
            angularGauge8.Base.FontSize = 12;
            angularGauge8.SectionsInnerRadius = 0.5;
            angularGauge8.LabelsStep = 0.5;
            angularGauge8.TickStep = 0.25;
            angularGauge8.Sections.Add(new AngularSection
            {
                FromValue = 0,
                ToValue = 1,
                Fill = System.Windows.Media.Brushes.LimeGreen
            });

            angularGauge8.Sections.Add(new AngularSection
            {
                FromValue = 1,
                ToValue = 2,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(247, 166, 37))
            });

            angularGauge8.Sections.Add(new AngularSection
            {
                FromValue = 2,
                ToValue = 3,
                Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(254, 57, 57))
            });

            #endregion
            #region 饼图加载

            Func<ChartPoint, string> labelPoint = chartPoint =>
                string.Format("{0}", chartPoint.Y);//, chartPoint.Participation
            pieChart1.LegendLocation = LegendLocation.Bottom;
            pieChart2.LegendLocation = LegendLocation.Bottom;   //指示图的信息


            #endregion
            #region 曲线设置
            var mapper = Mappers.Xy<MeasureModel>()
               .X(model => model.DateTime.Ticks)   //use DateTime.Ticks as X
               .Y(model => model.Value)           //use the value property as Y
               .Stroke(model => model.Value > 50 ? DangerBrush : System.Windows.Media.Brushes.LimeGreen)
               .Fill(model => model.Value > 50 ? DangerBrush : System.Windows.Media.Brushes.LimeGreen);

            //lets save the mapper globally.
            Charting.For<MeasureModel>(mapper);

            //the ChartValues property will store our values array
            ChartValues = new ChartValues<MeasureModel>();
            ChartValues1 = new ChartValues<MeasureModel>();
            ChartValues2 = new ChartValues<MeasureModel>();

            cartesianChart1.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Title="VOC: ",
                    Values = ChartValues,
                    PointGeometrySize = 14,
                    StrokeThickness = 4,
                    Stroke=System.Windows.Media.Brushes.White,
                    Fill=System.Windows.Media.Brushes.Transparent,
                    DataLabels=false,
                    FontSize=16,
                    Foreground=System.Windows.Media.Brushes.White

                }

            };
            cartesianChart1.AxisX.Add(new Axis
            {
                DisableAnimations = true,
                LabelFormatter = value => new System.DateTime((long)value).ToString("HH:mm:ss"),
                Separator = new Separator
                {
                    Step = TimeSpan.FromSeconds(2).Ticks
                }
            });
            cartesianChart2.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Title="VOC: ",
                    Values = ChartValues1,
                    PointGeometrySize = 12,
                    StrokeThickness = 3,
                    Stroke=System.Windows.Media.Brushes.White,
                    Fill=System.Windows.Media.Brushes.Transparent,
                    DataLabels=false,
                    FontSize=16,
                    Foreground=System.Windows.Media.Brushes.White
                }
            };
            cartesianChart2.AxisX.Add(new Axis
            {
                DisableAnimations = true,
                LabelFormatter = value => new System.DateTime((long)value).ToString("HH:mm:ss"),
                Separator = new Separator
                {
                    Step = TimeSpan.FromSeconds(1).Ticks
                }
            });
            cartesianChart3.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Title="PM2.5: ",
                    Values = ChartValues2,
                    PointGeometrySize = 12,
                    StrokeThickness = 3,
                    Stroke=System.Windows.Media.Brushes.White,
                    Fill=System.Windows.Media.Brushes.Transparent,
                    DataLabels=false,
                    FontSize=16,
                    Foreground=System.Windows.Media.Brushes.White
                }
            };
            cartesianChart3.AxisX.Add(new Axis
            {
                DisableAnimations = true,
                LabelFormatter = value => new System.DateTime((long)value).ToString("HH:mm:ss"),
                Separator = new Separator
                {
                    Step = TimeSpan.FromSeconds(1).Ticks
                }
            });

            SetAxisLimits(System.DateTime.Now);

            #endregion
            //Logger.Info("***********控件加载完成*************");

        }
        
        
        System.Windows.Media.Brush DangerBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(238, 83, 80));
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Width = 1920;
            this.Height = 1080;
            //Logger.Info("***********系统打开*************");                    
            comboBox1.SelectedIndex = 2;
            comboBox2.SelectedIndex = 2;           
            //if (RegistService.checkRegist() == true)
            //{
            //    lbRegistInfo.Visible = false;
            //    isRegist = true;
            //    Logger.Info("***********软件已注册*************");
            //}
            //else
            //{
            //    lbRegistInfo.Visible = true;
            //    lbRegistInfo.Text = "待注册，运行十分钟后自动关闭";
            //    Logger.Info("***********软件未注册*************");
            //    probationTimer.Start();
            //}
            #region 数据库时钟     
            dbTimer.Interval = Tim;

            #endregion
            #region PLC连接
            Task t = new Task(() =>
            {
                connectPLC(S7200SMART, 1);
                connectPLC(S7200SMART1, 2);
            });
            t.Start();
            
            #endregion
        }

        private void SetAxisLimits(System.DateTime now)
        {
            cartesianChart1.AxisX[0].MaxValue = now.Ticks + TimeSpan.FromSeconds(2).Ticks; // lets force the axis to be 100ms ahead
            cartesianChart1.AxisX[0].MinValue = now.Ticks - TimeSpan.FromSeconds(20).Ticks; //we only care about the last 8 seconds
            cartesianChart2.AxisX[0].MaxValue = now.Ticks + TimeSpan.FromSeconds(2).Ticks; // lets force the axis to be 100ms ahead
            cartesianChart2.AxisX[0].MinValue = now.Ticks - TimeSpan.FromSeconds(10).Ticks; //we only care about the last 8 seconds
            cartesianChart3.AxisX[0].MaxValue = now.Ticks + TimeSpan.FromSeconds(2).Ticks; // lets force the axis to be 100ms ahead
            cartesianChart3.AxisX[0].MinValue = now.Ticks - TimeSpan.FromSeconds(10).Ticks; //we only care about the last 8 seconds           
        }

        public static double zrSpeed = 0;
        public static double hhSpeed = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {          
            if (S7200SMART.IsConnected)
            {
                try
                {                    
                    double[] sdata = (double[])S7200SMART.Read(DataType.DataBlock, 1, 108, VarType.Real, 10);
                    double an   =Math.Round(sdata[0],2);
                    double temp = Math.Round(sdata[1], 2);
                    double humi = Math.Round(sdata[2], 2);
                    double h2s  = Math.Round(sdata[3], 2);
                    double voc  = Math.Round(sdata[4], 3)*100;
                    double kspeed = Math.Round(sdata[6], 1);
                    double kpress = Math.Round(sdata[7], 1);
                    double pspeed = Math.Round(sdata[8], 1);
                    zrSpeed = pspeed;
                    double ppress = Math.Round(sdata[9], 1);
                    
                    if (!zrIsDb)//存入数据库
                    {
                        zrIsDb = true;
                        int hgNum = GetHgNum(an, temp, humi, h2s, voc, 0);
                        try
                        {
                            MySqlHelp.InsertData(an, temp, humi, h2s, voc, 0, 1, hgNum, DateTime.Now);
                        }
                        catch (Exception ex)
                        {
                            //Logger.Error("1号定时存入数据库错误  " + ex.ToString());
                        }
                        //Logger.Info("***********1号定时写入数据库成功*************");
                    }
                    label21.Text = kspeed.ToString();
                    label22.Text = kpress.ToString();
                    label28.Text = pspeed.ToString();
                    label25.Text = ppress.ToString();
                
                    var now = System.DateTime.Now;
                    ChartValues.Add(new MeasureModel
                    {
                        DateTime = now,
                        Value = voc
                    });
                   
                    SetAxisLimits(now);                  
                    if (ChartValues.Count > 11) ChartValues.RemoveAt(0);

                    if (temp > angularGauge1.ToValue) temp = angularGauge1.ToValue;
                    if (humi > angularGauge2.ToValue) humi = angularGauge2.ToValue;
                    if (an >   angularGauge3.ToValue) an = angularGauge3.ToValue;
                    if (h2s >  angularGauge4.ToValue) h2s = angularGauge4.ToValue;

                    angularGauge1.Value = temp;
                    angularGauge2.Value = humi;
                    angularGauge3.Value = an;
                    angularGauge4.Value = h2s;

                    label35.Text = temp.ToString();
                    label34.Text = humi.ToString();
                    label27.Text = an.ToString();
                    label26.Text = h2s.ToString();
                }
                catch (Exception ex)
                {
                    //Logger.Error("定时采集错误  " + ex.ToString());
                    Console.WriteLine(ex.ToString());

                }
            }
            else
            {
                plcState(false,1);
                timer1.Stop();
            }
        }
        private void 报告ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Logger.Info("***********点击报告*************");
            reportWindow report = new reportWindow();
            report.ShowDialog();
        }
        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetRef();
            SetForm setform = new SetForm();
            //Logger.Info("***********点击设置*************");
            setform.ShowDialog();
        }
        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HelpForm helpform = new HelpForm();
            //Logger.Info("***********点击帮助*************");
            helpform.ShowDialog();
        }
        private void 日志ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogForm logform = new LogForm();
            //Logger.Info("***********点击日志*************");
            logform.ShowDialog();
        }
        private void 分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AnalysisForm analysisform = new AnalysisForm();
            //Logger.Info("***********点击分析*************");
            analysisform.ShowDialog();
        }
        private void 注册ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (isRegist)
            {
                System.Windows.Forms.MessageBox.Show("已注册！");
            }
            else
            {
                RegistForm registform = new RegistForm();
                //Logger.Info("***********点击注册*************");
                registform.ShowDialog();
            }
        }

        bool hhIsDb = false;
        bool zrIsDb = false;
        private void dbTimer_Tick(object sender, EventArgs e)
        {
            double useMemory = GetProcessUsedMemory();
            //Logger.Info("内存使用量: " + useMemory.ToString("0.0") + " M");
            hhIsDb = false;
            zrIsDb = false;
        }
        /// <summary>
        /// 上位机连接PLC，并根据NUM的值，判断所需要打开的定时器
        /// </summary>
        /// <param name="PLCName"></param>
        /// <param name="num"></param>
        private void connectPLC(Plc PLCName,int num)
        {
            if (!PLCName.IsConnected)
            {
                try
                {
                    PLCName.Open();
                    plcState(PLCName.IsConnected,num);
                    if (num == 1) timer1.Start();
                    if (num == 2) timer2.Start();

                }
                catch (Exception ex)
                {
                    //Logger.Error("PLC连接错误  " + ex.ToString());
                    Console.WriteLine("连接PLC失败！");
                    plcState(PLCName.IsConnected,num);
                }

            }
        }

        /// <summary>
        /// 显示PLC的状态，在picturebox中显示
        /// </summary>
        /// <param name="stat"> 指示PLC的状态 </param>
        /// <param name="num"> 指示PLC的标识号码 </param>
        private void plcState(bool stat,int num)
        {
            try
            {
                if (num == 1)
                {
                    if (stat)
                    {
                        //Logger.Info("***********PLC1连接成功*************");
                        pictureBox2.Image = 际海环境软件.Properties.Resources.success;
                        label4.Text = "PLC1连接成功";
                    }
                    else
                    {
                        //Logger.Info("***********PLC1连接失败*************");
                        pictureBox2.Image = 际海环境软件.Properties.Resources.error;
                        label4.Text = "PLC1连接失败";
                    }
                }
                if (num == 2)
                {
                    if (stat)
                    {
                        //Logger.Info("***********PLC2连接成功*************");
                        pictureBox4.Image = 际海环境软件.Properties.Resources.success;
                        label1.Text = "PLC2连接成功";
                    }
                    else
                    {
                        //Logger.Info("***********PLC2连接失败*************");
                        pictureBox4.Image = 际海环境软件.Properties.Resources.error;
                        label1.Text = "PLC2连接失败";
                    }
                }

            }
            catch (Exception ex)
            {
                //Logger.Error("PLC状态显示错误  " + ex.ToString());
                Console.WriteLine(ex.ToString());
            }

        }
       
       
        public static double[] Refval=new double[12];
        string[] Refstr = { "an_val", "temp_val", "humi_val", "h2s_val", "voc_val", "pm25_val" };
        //string[] Namestr = { "氨气", "温度", "湿度", "硫化氢", "VOC", "PM2.5"};
        private void GetRef()
        {           
            try
            {
                Refval=MySqlHelp.GetRefData();
            }
            catch (Exception ex)
            {
                //Logger.Error("获取参考值错误  " + ex.ToString());
            }
        }

        private string GetDaySet(int num)
        {
            string daySet =null;
            if (num == 0) { daySet = " INTERVAL 1 DAY"; }
            if (num == 1) { daySet = "INTERVAL 7 DAY"; }
            if (num == 2) { daySet = "INTERVAL 1 MONTH"; }
            if (num == 3) { daySet = "INTERVAL 1 YEAR"; }
            return daySet;
        }
        private int GetHgNum(double an,double temp,double humi,double h2s,double voc,double pm25)
        {
            int hgNum = 0;
            if (an < Refval[0] || an > Refval[1]) hgNum |= 1;
            if (temp < Refval[2] || temp > Refval[3]) hgNum |= 2;
            if (humi < Refval[4] || humi > Refval[5]) hgNum |= 4;
            if (h2s < Refval[6] || h2s > Refval[7]) hgNum |= 8;
            if (voc < Refval[8] || voc > Refval[9]) hgNum |= 16;
            if (pm25 < Refval[10] || pm25 > Refval[11]) hgNum |= 32;
            return hgNum;

        }
        private void GetHighWarnNum(int num)
        {
            string daySet = GetDaySet(num);          
            List<int> ints = new List<int>();
            try
            {
                for (int i = 0; i < 6; i++)
                {
                    int val = MySqlHelp.GetWarnNum(Refstr[i], Refval[i * 2 + 1], daySet, 1);
                    ints.Add(val);                   
                }             
                pieChart1.Series = new SeriesCollection
                {
                     new PieSeries
                     {
                         Title = "氨气",
                         Values = new ChartValues<int> {ints[0]},
                     },
                     new PieSeries
                     {
                         Title = "温度",
                         Values = new ChartValues<int> {ints[1]},
                     },
                     new PieSeries
                     {
                         Title = "湿度",
                         Values = new ChartValues<int> {ints[2]},
                     },
                      new PieSeries
                     {
                         Title = "硫化氢",
                         Values = new ChartValues<int> {ints[3]},
                     },
                       new PieSeries
                     {
                         Title = "VOC",
                         Values = new ChartValues<int> {ints[4]},
                     },
                     new PieSeries
                     {
                         Title = "PM2.5",
                         Values = new ChartValues<int> {ints[5]},
                     }                  
                 };            
                //Logger.Info("**********获取高温报警成功************");
            }
            catch (Exception ex)
            {
                //Logger.Error("获取高温报警错误  " + ex.ToString());  
            }
        }
        private void GetLowWarnNum(int num)
        {
            string daySet = GetDaySet(num);         
            List<int> ints = new List<int>();         
            try
            {              
                for (int i = 0; i < 6; i++)
                {
                    int val = MySqlHelp.GetWarnNum(Refstr[i], Refval[i * 2 + 1], daySet, 0);
                    ints.Add(val);
                }
                pieChart2.Series = new SeriesCollection
                {
                     new PieSeries
                     {
                         Title = "氨气",
                         Values = new ChartValues<double> {ints[0]},
                     },
                     new PieSeries
                     {
                         Title = "温度",
                         Values = new ChartValues<double> {ints[1]},
                     },
                     new PieSeries
                     {
                         Title = "湿度",
                         Values = new ChartValues<double> {ints[2]},
                     },
                      new PieSeries
                     {
                         Title = "硫化氢",
                         Values = new ChartValues<double> {ints[3]},
                     },
                       new PieSeries
                     {
                         Title = "VOC",
                         Values = new ChartValues<double> {ints[4]},
                     },
                     new PieSeries
                     {
                         Title = "PM2.5",
                         Values = new ChartValues<double> {ints[5]},
                     }
            };
                //Logger.Info("**********获取低温报警成功************");
            }
            catch (Exception ex)
            {
                //Logger.Error("获取低温报警错误  " + ex.ToString());             
            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetRef();
            GetHighWarnNum(comboBox1.SelectedIndex);
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetRef();
            GetLowWarnNum(comboBox1.SelectedIndex);
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            //Logger.Info("**********重新连接PLC************");
            connectPLC(S7200SMART,1);
        }
        public double GetProcessUsedMemory()
        {
            double usedMemory = 0;
            try
            {
                usedMemory = Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0;
            }
            
            catch(Exception ex)
            {
                //Logger.Error("获取内存使用错误 "+ex.ToString());
            }
            return usedMemory;
        }

        int count = 0;
        private void probationTimer_Tick(object sender, EventArgs e)
        {
            count++;
            if (count > 300 && isRegist == false)
            {
                //Logger.Info("************试运行结束*************");
                this.Close();//在其他界面时，会报错
            }         
            if (isRegist == true)
            {
                count = 0;
                probationTimer.Enabled = false;
                lbRegistInfo.Visible = false;//thread线程不能访问form线程              
                return;
            }
           
        }
        private void timer2_Tick(object sender, EventArgs e)
        {          
            if (S7200SMART1.IsConnected)
            {
                try
                {                  
                    double[] sdata = (double[])S7200SMART1.Read(DataType.DataBlock, 1, 108, VarType.Real, 10);                   
                    double an     = Math.Round(sdata[0],2);
                    double temp   = Math.Round(sdata[1],2);
                    double humi   = Math.Round(sdata[2],2);
                    double h2s    = Math.Round(sdata[3],2);
                    double voc    = Math.Round(sdata[4],3)*100;
                    double pm25   = Math.Round(sdata[5],2);
                    double kspeed = Math.Round(sdata[6], 1);
                    double kpress = Math.Round(sdata[7], 1);
                    double pspeed = Math.Round(sdata[8], 1);
                    double ppress = Math.Round(sdata[9], 1);

                    hhSpeed = pspeed;


                    if (!hhIsDb)
                    {
                        hhIsDb = true;
                        int hgNum = GetHgNum(an, temp, humi, h2s, voc, pm25);
                        try
                        {
                            MySqlHelp.InsertData(an, temp, humi, h2s, voc, pm25, 1, hgNum, DateTime.Now);
                        }
                        catch (Exception ex)
                        {
                            //Logger.Error("2号定时存入数据库错误  " + ex.ToString());
                        }
                        //Logger.Info("***********2号定时写入数据库成功*************");
                    }

                    label42.Text = kspeed.ToString();
                    label39.Text = kpress.ToString();
                    label31.Text = pspeed.ToString();
                    label33.Text = ppress.ToString();

                    var now = System.DateTime.Now;
                    
                    ChartValues1.Add(new MeasureModel
                    {
                        DateTime = now,
                        Value = voc
                    });
                 
                    ChartValues2.Add(new MeasureModel
                    {
                        DateTime = now,
                        Value = pm25
                    });

                    SetAxisLimits(now);
                    if (ChartValues1.Count > 6) ChartValues1.RemoveAt(0);
                    if (ChartValues2.Count > 6) ChartValues2.RemoveAt(0);

                    if (temp > angularGauge5.ToValue) temp = angularGauge5.ToValue;
                    if (humi > angularGauge6.ToValue) humi = angularGauge6.ToValue;
                    if (an > angularGauge7.ToValue)   an = angularGauge7.ToValue;
                    if (h2s > angularGauge8.ToValue)  h2s = angularGauge8.ToValue;
                    angularGauge5.Value = temp;
                    angularGauge6.Value = humi;
                    angularGauge7.Value = an;
                    angularGauge8.Value = h2s;

                    label40.Text = temp.ToString();
                    label38.Text = humi.ToString();
                    label37.Text = an.ToString();
                    label36.Text = h2s.ToString();
                }
                catch (Exception ex)
                {
                    //Logger.Error("定时采集错误  " + ex.ToString());
                    //Console.WriteLine(ex.ToString());
                }

                
            }
            else
            {
                plcState(false, 2);
                timer2.Stop();
            }
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            //Logger.Info("**********重新连接PLC2************");
            connectPLC(S7200SMART1, 2);
        }
    }
}
